﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace Btstack
{
    public partial class Bluetooth
    {
        private readonly BtstackPacketHandlerType AttPacketHandlerPtr;

        private void AttPacketHandler(byte type, ushort channel, IntPtr PacketPtr, ushort size)
        {
            if (type != HCI_EVENT_PACKET)
                return;

            byte[] packet = new byte[size];
            Marshal.Copy(PacketPtr, packet, 0, size);

            ushort handle;

            switch (HciEventPacketGetType(packet))
            {
                case ATT_EVENT_CONNECTED:
                    handle = AttEventConnectedGetHandle(packet);
                    Console.WriteLine($"ATT connected, handle 0x{handle:x4}");
                    break;

                case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
                    var mtu = AttEventMtuExchangeCompleteGetMTU(packet) - 3;
                    handle = AttEventMtuExchangeCompleteGetHandle(packet);
                    Console.WriteLine($"ATT MTU = {mtu} => handle 0x{handle:x4}");
                    break;

                case ATT_EVENT_CAN_SEND_NOW:
                    Console.WriteLine("Can send now");
                    break;

                case ATT_EVENT_DISCONNECTED:
                    handle = AttEventDisconnectedGetHandle(packet);
                    Console.WriteLine($"ATT disconnected, handle 0x{handle:x4}");
                    break;

                default:
                    break;
            }
        }

        public void StartAdvertising(string name, byte[] ProfileData, AttWriteCallbackType WriteCallback)
        {
            AttServerInit(ProfileData, null, WriteCallback);

            ushort AdvIntMin = 0x0030;
            ushort AdvIntMax = 0x0030;
            byte[] NullAddr = new byte[6];
            var AdvData = new List<byte>
            {
                // Flags general discoverable, BR/ EDR not supported
                0x02, BLUETOOTH_DATA_TYPE_FLAGS, 0x06
            };

            AdvData.Add((byte)(name.Length + 1));
            AdvData.Add(BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME);
            AdvData.AddRange(System.Text.Encoding.UTF8.GetBytes(name));

            // Incomplete List of 16-bit Service Class UUIDs -- FF10 - only valid for testing!
            AdvData.Add(0x03);
            AdvData.Add(BLUETOOTH_DATA_TYPE_INCOMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS);
            AdvData.AddRange(new byte[] { 0x10, 0xff });

            GapAdvertisementsSetParams(AdvIntMin, AdvIntMax, AdvType.AdvInd, BdAddrType.LePublic, NullAddr, 0x07, 0x00);
            GapAdvertisementsSetData(AdvData.ToArray());
            GapAdvertisementsEnable(true);
        }

        public void StopAdvertising()
        {
            GapAdvertisementsEnable(false);
        }
    }
}
